import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:pornhub_app/services/app_service.dart';
import 'package:pornhub_app/utils/ad_jump.dart';

import '../../http/http_service.dart';
import '../../model/advertisements/app_update.dart';
import '../../routes/routes.dart';
import '../../utils/color.dart';
import '../../utils/context_link.dart';
import '../app_bg_image_button_view.dart';
import '../text_view.dart';

Future<AppUpdateModel?> checkVersion() async {
  if (!kIsWeb) {
    try {
      final updates = await httpInstance.get<AppUpdateModel>(
          url: 'sys/version/update', complete: AppUpdateModel.fromJson);
      if (updates is AppUpdateModel && updates.hasNewVersion == true) {
        return updates;
      }
      return null;
    } catch (e) {
      return null;
    }
  }
  return null;
}

Widget showUpdateDialog(AppUpdateModel? updates) {
  // var isUpdateing = false.obs;
  // var progress = 0.0.obs;
  return SizedBox(
    width: 300.w,
    height: 450.w,
    child: Stack(
      children: [
        Positioned(
          top: 25.w,
          left: 0,
          right: 0,
          bottom: 0,
          child: Container(
            width: double.infinity,
            height: double.infinity,
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(12.w),
            ),
            padding: EdgeInsets.symmetric(horizontal: 15.w),
            child: Column(
              children: [
                SizedBox(height: 80.w),
                TextView(
                  text: "版本升级",
                  color: COLOR.hexColor('#333'),
                  fontSize: 20.w,
                  fontWeight: FontWeight.w600,
                ),
                SizedBox(height: 10.w),
                Expanded(
                  child: SingleChildScrollView(
                    child: Text.rich(
                        TextSpan(
                          children: contextLink(
                            " ${updates?.info}",
                            TextStyle(
                                color: COLOR.hexColor('#eb29c6'),
                                fontSize: 14.w),
                          ),
                        ),
                        style: TextStyle(
                            color: COLOR.color_333333, fontSize: 12.w)),
                  ),
                ),
                SizedBox(height: 10.w),
                Column(
                  children: [
                    InkWell(
                      onTap: () {
                        SmartDialog.dismiss();
                        Get.toShare();
                      },
                      child: _buildButton("更新前保存您的凭证"),
                    ),
                    SizedBox(height: 10.w),
                    Row(
                      children: [
                        Expanded(
                          flex: 1,
                          child: InkWell(
                            onTap: () {
                              SmartDialog.dismiss();
                            },
                            child: _buildButton("取消"),
                          ),
                        ),
                        SizedBox(width: 10.w),
                        Expanded(
                          flex: 1,
                          child: InkWell(
                            onTap: () {
                              // isUpdateing.value = true;
                              // _androidInnerAppDownloadApk(
                              //     updates?.link ?? '',
                              //     onProgressCall: (_progress) {
                              //   progress.value = _progress;
                              // });
                              final url = Get.find<AppService>().androidLandURL;
                              jumpExternalAddress(url ?? '', null);
                            },
                            child: AppBgImageButtonView(
                              width: 300.w,
                              height: 40.w,
                              imageBg: "assets/ann/ic_update.png",
                              fit: BoxFit.cover,
                              borderRadius: BorderRadius.circular(20.w),
                              text: "",
                              textColor: COLOR.white,
                              textSize: 16.w,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
                SizedBox(height: 20.w),
              ],
            ),
          ),
        ),
        Positioned(
          top: 0,
          left: 0,
          right: 0,
          child: Container(
            height: 84.w,
            alignment: Alignment.center,
            child: Image.asset(
              'assets/ann/update_title.png',
              width: 149.w,
              height: 84.w,
            ),
          ),
        ),
      ],
    ),
  );
}

Widget _buildButton(String text) {
  return Container(
    width: double.infinity,
    height: 40,
    decoration: BoxDecoration(
      borderRadius: BorderRadius.circular(20.w),
      color: COLOR.white,
      border: Border.all(color: COLOR.color_B93FFF, width: 1.w),
    ),
    alignment: Alignment.center,
    child: Text(
      text,
      style: TextStyle(
        color: COLOR.color_B93FFF,
        fontSize: 16.w,
      ),
      maxLines: 1,
    ),
  );
}

// _androidInnerAppDownloadApk(String apkURL,
//     {Function(double)? onProgressCall}) async {
//   if (apkURL.isEmpty) {
//     EasyToast.show('下载链接非法！');
//     return;
//   }

//   final res = await filedownloader.downloadMediaFile(apkURL,
//       onProgress: (count, total) {
//     double progress = (count / total) * 100.0.toDouble();

//     onProgressCall?.call(progress);
//   });

//   if (res == FileDownloaderResult.fail) {
//     EasyToast.show("下载失败，请重试!");
//     return;
//   }
//   if (res == FileDownloaderResult.success) {
//     final filePath = await filedownloader.fileSavePathForNative(apkURL);
//     final insRes = await InstallPlugin.install(filePath);
//     EasyToast.show(insRes['isSuccess'] == true
//         ? '安装成功'
//         : '安装失败:${insRes['errorMessage'] ?? ''}');
//     return;
//   }
// }
